/*
 * 文件名： ScanPayPabServerRes.java
 * 
 * 工程名称: bis-web
 *
 * Gopay
 *
 * 创建日期： 2017年8月17日
 *
 * Copyright(C) 2017, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.web.controller.scan;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.pab.agpay.res.PayNotifyResMsg;
import com.gopay.common.domain.bank.wechat.scan.res.ScanPayServerNotifyMsg;
import com.gopay.common.util.FastJsonUtil;

/**
 * 扫码平安银行渠道异步服务端通知
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2017年8月17日
 */
@Controller
@Scope("prototype")
public class ScanPayPabServerRes extends ScanPayBankResBase {
	private static Log logger = LogFactory.getLog(ScanPayPabServerRes.class);

	@RequestMapping(value = "/scanPayPabServerRes")
	protected void execute(HttpServletRequest request, HttpServletResponse response) {
		logger.error("---------------ScanPayPabServerRes  bankback ---------------");
		super.execute(request, response);

	}

	@SuppressWarnings("unchecked")
	@Override
	protected BaseMessage buildMessage(HttpServletRequest request) {
		Map<String, String> params = new TreeMap<String, String>();
		// 取出所有参数是为了验证签名
		Enumeration<String> parameterNames = request.getParameterNames();
		while (parameterNames.hasMoreElements()) {
			String parameterName = parameterNames.nextElement();
			params.put(parameterName, request.getParameter(parameterName));
		}
		String jsonStr =FastJsonUtil.collectToString(params);
		PayNotifyResMsg notifyMsg=new PayNotifyResMsg();
		notifyMsg.setOrd_no(params.get("ord_no"));
		notifyMsg.setAmount(params.get("amount"));
		notifyMsg.setOut_no(params.get("out_no"));
		notifyMsg.setPay_time(params.get("pay_time"));
		notifyMsg.setRand_str(params.get("rand_str"));
		notifyMsg.setSign(params.get("sign"));
		notifyMsg.setStatus(params.get("status"));
		notifyMsg.setTimestamp(params.get("timestamp"));
		
		ScanPayServerNotifyMsg message = new ScanPayServerNotifyMsg();
		if("1".equals(notifyMsg.getStatus())){
			message.setPay_result("0");
		}	
		message.setBankOrderId(notifyMsg.getOut_no());
		message.setAmount(new BigDecimal(notifyMsg.getAmount()).divide(new BigDecimal(100)));
		//message.setBank(BankConstants.BANK_LOGO_WECHAT);
		message.setBankBusProd(BisBankBusinessProd._16);
		message.setSignMessage(notifyMsg.getSign());
		message.setPlainMessage(jsonStr);
		message.setFront(false);
		return message;
	}

	@Override
	protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
		ScanPayServerNotifyMsg message = (ScanPayServerNotifyMsg) result.getModel("res");
		OrderInfo orderInfo = new OrderInfo();
		if (message != null) {
			if ("0".equals(message.getPay_result())) {
				orderInfo.setOrderId(message.getOrderId());
				orderInfo.setAmt(message.getAmount().toString());
				orderInfo.setNotifyNum("1");
				orderInfo.setPayStatus("00");
				orderInfo.setRetCode("00");
				orderInfo.setRetMsg("");
				orderInfo.setIsNotify(true);
				orderInfo.setBankName(message.getBank());
			} else {
				orderInfo.setOrderId(message.getOrderId());
				orderInfo.setAmt(message.getAmount().toString());
				orderInfo.setNotifyNum("1");
				orderInfo.setPayStatus("01");
				orderInfo.setRetCode("01");
				orderInfo.setRetMsg("");
				orderInfo.setIsNotify(true);
				orderInfo.setBankName(message.getBank());
			}
		}
		return orderInfo;	
	}

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected boolean notifyBank(HttpServletResponse response, OrderInfo orderInfo) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			// 通知民生银行成功接收银行通知
			String notifyMsg = "notify_success";
			logger.info("notifyBank " + orderInfo.getBankName() + " send content: \n[" + notifyMsg + "]");
			response.setContentLength(notifyMsg.getBytes().length);
			response.getOutputStream().write(notifyMsg.getBytes());
			response.getOutputStream().close();
			return true;
		} catch (IOException e) {
			logger.info(e.getMessage());
		}
		return true;
	}

}
